package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author atguigu-mqx
 */
@Component
public class OrderReceiver {

    //  获取到服务层对象
    @Autowired
    private OrderService orderService;

    //  监听消息！
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId , Message message, Channel channel){
        try {
            //  取消订单业务逻辑！
            if (orderId!=null){
                //  取消订单！
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus())
                && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  取消订单业务！
                    orderService.cancelOrder(orderId);
                }
            }
        } catch (Exception e) {
            //  记录日志。。。。 数据。。。。。
            e.printStackTrace();
        }
        //  手动确认消息！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId, Message message, Channel channel){
        try {
            //  判断订单Id
            if (orderId!=null){
                //   修改订单状态！
                this.orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                //  发送消息给库存！
                this.orderService.sendOrderStatus(orderId);
            }
        } catch (Exception e) {
            //  记录日志。。。。 数据。。。。。
            e.printStackTrace();
        }
        //  手动确认消息！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //  监听减库存结果！
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void wareOrder(String strJson,Message message,Channel channel){
        try {
            //  判断
            if(!StringUtils.isEmpty(strJson)){
                //  需要将strJson 这个Json数据转换为java 能操作的对象！
                Map map = JSON.parseObject(strJson, Map.class);
                //  获取map 中的数据！
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                //  判断状态
                if ("DEDUCTED".equals(status)){
                    //  说明减库存成功！
                    this.orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
                }else {
                    //  说明减库存失败！
                    this.orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
                    //  1.  库存不足，则需要调用其他仓库的货物！  2.  亲，不好意思......
                }
            }
        } catch (NumberFormatException e) {
            //  记录订单Id ，写入哪条失败！
            e.printStackTrace();
        }

        //  手动确认消息！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
